package it.francescogabbrielli.android.solidalapp;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.Executor;

public class SerialExecutor implements Executor {

	final Queue<Runnable> tasks = new LinkedList<Runnable>();
	Runnable active;

	public SerialExecutor() {
	}

	public synchronized void execute(final Runnable r) {
		tasks.offer(new Runnable() {
			public void run() {
				try {
					r.run();
				} finally {
					scheduleNext();
				}
			}
		});
		if (active == null)
			scheduleNext();
	}

	protected synchronized void scheduleNext() {
		if ((active = tasks.poll()) != null)
			active.run();
	}
}
